﻿using System;
using AutoStopApp.Core;
using AutoStopData.BussinessLogic;
using Telerik.Charting;
using System.Data;

namespace AutoStopApp.Pages
{
    public partial class Activity : AjaxPage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            RefreshButton.Click += RefreshButtonClick;
            Load += PageLoad;
            ActivityChart.ItemDataBound += ActivityChartItemDataBound;
        }

        void PageLoad(object sender, EventArgs e)
        {
            AddAjaxSetting(RefreshButton, ChartPanel);
            if (!IsPostBack)
            {
                datDisplayedDate.SelectedDate = DateTime.Now;
                ReloadData();
            }
        }

        void RefreshButtonClick(object sender, EventArgs e)
        {
            ReloadData();
        }

        private void ReloadData()
        {
            var selectedDate = DateTime.Now;
            if (datDisplayedDate.SelectedDate != null)
            {
                selectedDate = datDisplayedDate.SelectedDate.Value;
            }
            var activities = Sessions.GetActivities(selectedDate);
            ActivityChart.DataSource = activities;
            ActivityChart.DataBind();
            ActivityChart.Height = 70 + activities.Count * 50;

            ActivityGrid.DataSource = activities;
            ActivityGrid.DataBind();
        }

        protected void ActivityChartItemDataBound(object sender, ChartItemDataBoundEventArgs e)
        {
            var dataView = (DataRowView)e.DataItem;
            e.SeriesItem.ActiveRegion.Tooltip = String.Format("Čas {0}", dataView["Time"]);
        }

        protected String FormatDateTime(DateTime input)
        {
            String retVal = input.ToString("F");
            return retVal;
        }

        protected String FormatTimeSpan(TimeSpan input)
        {
            var retVal = input.ToString("hh") + ":" + input.ToString("mm") + ":" + input.ToString("ss");
            return retVal;
        }

        protected String GetStatusIcon(ActivitySummary activitySummary)
        {
            var retVal = "/images/icons16/status_offline.png";
            if (!activitySummary.HasLoggedOut && activitySummary.LastAccess.AddMinutes(5) > DateTime.Now)
            {
                retVal = "/images/icons16/status_online.png";
            }
            return retVal;
        }

        protected String GetTimeToNow(DateTime dateTime)
        {
            var difference = DateTime.Now.Subtract(dateTime);
            return FormatTimeSpan(difference);
        }
    }
}